import { PureComponent } from 'react';
import { TreeSelect } from 'antd';
const { TreeNode } = TreeSelect;

class SelectOrganTree extends PureComponent {
  state = {
    value: undefined,
    treeData: [
    	{ title: '机构', key: '000000000000',org_id:'',org_code:"0000" },
    ],
  };

	constructor(props) {
	  super(props);
		this.state.value = props.orgValues;
  }
	
  onChange = (value,label,extra) => {
  		
  	if(extra.triggerNode.props.dataRef.key != '000000000000') {
	  	  const { selectedOrganTreeValue } = this.props;
    		selectedOrganTreeValue(extra);
    		this.setState({ value });
  	}
  };
  
  onSelect = value => {

  }
  
  onTreeExpand = expandedKeys => {

  }
  
  onLoadData = (treeNode) => {
	    const { dispatch,requestModelName } = this.props;
	    const params = {
	      parentid: treeNode.props.dataRef.key,
	    };
	    return new Promise((resolve) => {
			    if (treeNode.props.children) {
			      resolve();
			      return;
			    }
			    dispatch({
			        type: requestModelName + "/get_proorgtree_by_parentid",
			        payload: params,
			        callback: () => {
			          const { selectOrganTree: { list } } = this.props;
			          treeNode.props.dataRef.children = list;
			          this.setState({
			          	treeData: [...this.state.treeData],
			          });
			          resolve();
			        }
			     });
	    });
  };

	renderTreeNodes = data =>
	    data.map(item => {
		      if (item.children) {
		        return (
		    	    <TreeNode title={item.title} key={item.key} dataRef={item}  value={item.title}>
			            {this.renderTreeNodes(item.children)}
			         </TreeNode>
		        );
		      }
		      return <TreeNode {...item} value={item.title} dataRef={item} title={item.title} key={item.key}/>;
	});
	
  render() {
    return (
      <TreeSelect
      	showSearch
        value={this.state.value}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder="请选择机构"
        treeDefaultExpandAll
        onSelect={this.onSelect}
        onChange={this.onChange}
        onTreeExpand={this.onTreeExpand}
        loadData={this.onLoadData}
      >
       		{this.renderTreeNodes(this.state.treeData)}
      </TreeSelect>
    );
  }
}

export default SelectOrganTree;